package com.jyj.springbootshiro.comm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

/**
 * @class: com.jyj.springbootshiro.comm.UserRealm
 * @description: 自定义权限域
 * @author: jiangzengkui
 * @company: 教育家
 * @create: 2021-01-05 15:02
 */
public class UserRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("获得相关权限===================");
        //得到登录用户账号
        String login_code=(String) principalCollection.getPrimaryPrincipal();
        //获得角色信息
        Set<String> roles=getRole(login_code);

        //获得权限信息
        Set<String> permissions=getPermission(login_code);

        //new  SimpleAuthorizationInfo,设置相关的角色和权限数据
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();

        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("登录==============================");
        //用户名+密码
        String name = "root";
        String password="123";
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        if (!token.getUsername().equals(name)){
            return null;    //return null 会自动抛出异常
        }
        //密码认证，shiro做
        return new SimpleAuthenticationInfo("",password,"");
    }

    /**模拟从数据库
     * 通过用户账号获得角色信息
     * @param login_code
     * @return
     */
    private Set<String> getRole(String login_code) {
        Set<String> roles=new HashSet<>();
        roles.add("role1");
        roles.add("role2");
        roles.add("role3");
        return roles;
    }

    /**
     * m模拟从数据库获得权限数据
     * @param login_code
     * @return
     */
    private Set<String> getPermission(String login_code) {
        Set<String> permission=new HashSet<>();
        permission.add("user:delete");
        permission.add("user:update");
        permission.add("user:create");
        return permission;
    }
}